<?php
  require_once "DB.php";
  include_once("./libraries/authentication.inc.php");
  include_once("./libraries/db.inc.php");
  

  session_start();

  $connection = DB::connect($dsn, $options);

  if (DB::isError($connection)) {
    trigger_error($connection->getMessage(), E_USER_ERROR);
  }

  //register and clear our errors array
  if (isset($_SESSION["signupErrors"])) {
    unset($_SESSION["signupErrors"]);
  }
  $_SESSION["signupErrors"] = array();

  //set up an array for the POST vars
  $_SESSION["signupFormVars"] = array();

  $_SESSION["signupFormVars"]["username"] = $_POST["signupUsername"];
  $_SESSION["signupFormVars"]["pass1"] = $_POST["signupPass1"];
  $_SESSION["signupFormVars"]["pass2"] = $_POST["signupPass2"];

  if(strlen($_SESSION["signupFormVars"]["pass1"]) == 0) {
    $_SESSION["signupErrors"]["pass1"] = "You did not type in a password.";
  }
  elseif($_SESSION["signupFormVars"]["pass1"] != $_SESSION["signupFormVars"]["pass2"]) {
    $_SESSION["signupErrors"]["pass1"] = "Passwords must match EXACTLY.";
  }

  if(userExists($_SESSION["signupFormVars"]["username"],
                $connection)) {
    $_SESSION["signupErrors"]["username"] = "The username you selected is already in use in the system.";
  }

  if(count($_SESSION["signupErrors"]) > 0) {
    //try again...
    header("Location: signup.php");
    $connection->disconnect();
    exit;
  }

  //hooray! we made it, now put it into the database
  newUser($_SESSION["signupFormVars"]["username"],
          $_SESSION["signupFormVars"]["pass1"],
          $connection);

  //clear out the variables
  unset($_SESSION["signupFormVars"]);
  unset($_SESSION["signupErrors"]);

  $_SESSION["message"] = "You have successfully signed up for the system.";

  header("Location: login.php");  
  $connection->disconnect();
?>
